<!-- 全部项目 -->
<template>
  <div>
    <!-- 功能区 开始 CRC和PM进来是加入项目-->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="actionAdd" v-if="$auth('PROJECT.PROJECT_ADD')">新增项目</a-button>
      <a-button type="primary" icon="plus" @click="clickJoinProject" v-if="$isSystem()">加入项目</a-button>
    </div>
    <!-- 表格开始 -->
    <s-table
      ref="table"
      size="default"
      :row-key="record => record.id"
      :columns="columns"
      :data="loadData"
      :scroll="{ x: 1300 }">
      <span slot="createTime" slot-scope="text, record">{{ record.createTime | moment }}</span>
      <span slot="status" slot-scope="text, record">
        <template v-if="record.status == 1">未启动</template>
        <template v-if="record.status == 2">进行中</template>
        <template v-if="record.status == 3">关闭</template>
      </span>
      <template slot="id" slot-scope="text, record, index">
        {{ index | getPageIndex($refs.table) }}
      </template>
      <span slot="action" slot-scope="text, record">
        <template>
          <!-- <a @click="openEditor(record)" v-if="$auth('PROJECT.PROJECT_EDIT')">编辑</a>
          <a-divider type="vertical" v-if="$auth('PROJECT.PROJECT_EDIT')" /> -->
          <a @click="actionDetail(record)" v-if="$auth('PROJECT.PROJECT_DETAIL')">详情</a>
          <!-- <a-divider type="vertical" v-if="$auth('PROJECT.PROJECT_DETAIL')" />
          <a-popconfirm
            :title="dynamicTitle"
            ok-text="确定"
            cancel-text="取消"
            @visibleChange="handleVisibleChange(record)"
            @confirm="confirm(record)"
            v-if="$auth('PROJECT.PROJECT_DELETE')"
          >
            <a>删除</a>
          </a-popconfirm> -->
          <!-- <a-divider type="vertical" /> -->
          <!-- <a @click="financialDetail(record)">查看项目</a> -->
        </template>
      </span>
    </s-table>
    <AddModal
      :visible="visible"
      :isEditProject="isEditProject"
      @modalOk="addSubmit"
      @modalCancel="addCancel"
      @getLatestSponsor="getSponsorList"
      :openType="openType"
      :editContent="modify"
      :phaseListInfo="phaseList"
      :businessList="business"
    />
    <JoinProjectModal :joinProjectVisible="joinProjectVisible" @closeJoinProject="closeJoinProject" />
  </div>
</template>

<script>
import monitor from '@/utils/monitor'
import index from '@/monitor/views/overview/allItems/index'

import { getListAdmin } from '@/api/overview/bill'
import moment from 'moment'
import AddModal from './AddModal.vue'
import JoinProjectModal from './JoinProjectModal.vue'
import { getSponsorList } from '@/api/system/user'
import {
  getProjectList,
  getProjectAdd,
  getProjectDelete,
  getProjectUpdate,
  getProjectDetail
} from '@/api/overview/contract'
import { getUnread } from '@/api/system/message'
// const state = {
//   // 全局管理的数据存储
//   isLogin: '0',
//   ser: null,
//   token: localStorage.getItem('token') ? localStorage.getItem('token') : '' // token
// }

const watch = monitor(index)

export default {
  components: {
    AddModal,
    JoinProjectModal
  },
  props: {
    // 全部没状态1啥也不是  2进行中 3关闭状态
    switchState: {
      type: Number,
      default: null
    }
  },
  name: '',
  data () {
    return {
      userInformation: '', // 用户账号
      business: [],
      loading: false,
      advanced: false,
      joinProjectVisible: false,
      isEditProject: false,
      dynamicTitle: '是否要删除此行？',
      phaseList: [],
      msg: [],
      modify: {}, // 编辑某一行
      openType: 0, // 通过这个判断 状态是 添加 编辑 详情
      // tab切换时，更改 queryParam 中的状态字段。
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getProjectList({ ...parameter, ...this.queryParam }).then(res => {
          this.msg = res
          this.$emit('sendMsg', this.msg)
          return res.page
        })
      },
      // 表头
      columns: [
        {
          title: '序号',
          width: '80px',
          dataIndex: 'id',
          scopedSlots: { customRender: 'id' }
        },
        {
          title: '项目编号',
          width: '150px',
          dataIndex: 'no'
        },
        {
          title: 'PROTOCOL',
          width: '150px',
          dataIndex: 'protocolNo'
        },
        {
          title: '项目名称',
          width: '250px',
          dataIndex: 'name'
        },
        {
          title: '申办方',
          width: '150px',
          dataIndex: 'sponsorName'
        },
        {
          title: '立项时间',
          dataIndex: 'createTime',
          width: '150px',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: '项目负责人',
          width: '150px',
          dataIndex: 'pmName'
        },
        {
          title: '项目状态',
          dataIndex: 'status',
          width: '150px',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '业务人员',
          width: '150px',
          dataIndex: 'businessName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      currentId: null,
      visible: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }
    }
  },
  watch: {
    switchState (newv) {
      if (newv === null || newv === 1 || newv === 2 || newv === 3) {
        this.queryParam.status = newv
        this.$refs.table.refresh(true)
      }
      console.log('参数', this.switchState)
    }
  },
  created () {
    this.getRoleList()

    getUnread().then(res => {
      this.$globalVue.$emit('unReadMsgCount', res)
    })
  },
  mounted () {
    this.browsePage()
    this.$store.commit('changeActiveKey', 0)
  },
  methods: watch({
    getRoleList () {
      getListAdmin({
      }).then(res => {
        this.business = res
      })
    },
    // 下拉列表搜索
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 翻页事件
    changePage (page, pageSize) {
      this.page.pageNumber = page
      this.page.pageSize = pageSize
      this.$refs.table.refresh(true)
    },
    // 加入项目对话框关闭
    closeJoinProject (val) {
      this.joinProjectVisible = false
      if (val) {
        this.$refs.table.refresh(true)
      }
    },
    // 点击加入项目
    clickJoinProject () {
      this.joinProjectVisible = true
    },
      // 查看某一个单号的付款详情
    actionDetail (record) {
      this.toJump(record)
      /*
      // 这里获取roleName,在store获取会置空
      if (store.getters.userInfo.isAdmin !== 1) {
        getInfo({
          proId: record.id
        }).then(res => {
          localStorage.setItem('curRole', res.user.roleName)
        })
      }
      // 非系统人员调用接口
      if (store.getters.userInfo.isAdmin !== 1) {
        // console.log('store.getters', store.getters.userInfo.isAdmin)
        store
          .dispatch('GetInfo', {
            proId: record.id
          })
          .then(res => {
            const roles = res && res.role
            this.usenformation = store.getters.userInfo.roleName
            store
              .dispatch('GenerateRoutes', {
                roles
              })
              .then(() => {
                // 根据roles权限生成可访问的路由表
                // 动态添加可访问路由表
                router.addRoutes(store.getters.addRouters)
                this.toJump(record)
              })
          })
      } else {
        this.usenformation = store.getters.userInfo.roleName
        this.toJump(record)
      }
      */
    },
    // 路由跳转
    toJump (record) {
      // if (this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.FINANCE.value)) {
      //   this.$store.dispatch('EnterProject', record).then(res => {
      //     this.$router.push({
      //       name: 'Treasure',
      //       query: {
      //       // id: record.id
      //     }
      //   })
      // })
      // } else {
        this.$store.dispatch('EnterProject', record).then(res => {
          this.$router.push({
            name: 'Responsible',
            query: {
              // id: record.id
            }
          })
        })
      // }
    },
    handleVisibleChange (record, visible) {
      if (record.status === 2) {
        this.dynamicTitle = '项目进行中禁止删除'
      } else {
        this.dynamicTitle = '是否要删除此行？'
      }
    },
    // 点击删除这一行
    confirm (record) {
      getProjectDelete({
        id: record.id,
        status: record.status
      }).then(res => {
        this.$message.success('删除成功')
        this.$refs.table.refresh(true)
      })
    },
    // 点击新增弹框
    actionAdd () {
      this.getSponsorList()
      this.modify = {}
      this.openType = 0
      this.visible = true
      this.isEditProject = false
    },
    // 请求申办方列表
    getSponsorList () {
      getSponsorList({ code: 10001011 }).then(res => {
        this.phaseList = res
      })
    },
    // 点击编辑这一行
    openEditor (record) {
      this.getSponsorList()
      this.currentId = record.id
      getProjectDetail({
        id: record.id
      }).then(res => {
        const { protocolNo, name, status, stage, budget, no, contractNo, buildTime, createrId, businessName } = res
        const sponsorIds = res.sponsorIds.split(',').map(Number) // 注：后端返回的是个字符串需将其转为数组(split分割后是个string数组，map方法将其转为number数组)
        this.modify = {
          protocolNo,
          name,
          sponsorIds,
          status,
          stage,
          budget,
          no,
          contractNo,
          buildTime,
          createrId,
          businessName
        }
        this.modify.buildTime = moment(this.modify.buildTime).format('YYYY-MM-DD')
        this.openType = 1
        setTimeout(() => {
          this.visible = true
        }, 10)
      })
    },
    addCancel () {
      this.visible = false
    },
    // 点击确认新增
    addSubmit (e) {
      if (this.openType === 0) {
        getProjectAdd(e)
          .then(res => {
            this.visible = false
            this.$message.success('添加成功')
            this.$refs.table.refresh(true)
          })
          .catch(() => {
            // this.visible = false
          })
        console.log('添加转入信息', e)
      } else {
        delete e.buildTime
        delete e.businessName
        console.log('e', e)
        getProjectUpdate({
          ...e,
          id: this.currentId
        }).then(res => {
          this.$message.success('修改成功')
          this.visible = false
           this.$refs.table.refresh(true)
        })
        console.log('编辑转入信息', e)
        console.log('编辑转入id', this.currentId)
      }
    },
    // 页面浏览埋点
    browsePage () {}
  })
}
</script>
<style scoped lang="scss"></style>
